﻿using IDLETD.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace IDLETD.Agent
{
    public class SportAgent
    {
        public List<Point> Path { get; set; }
        public Point TargetPoint { get; set; }
        public BaseGameObject Onwer { get; set; }

        public bool Move()
        {
            double onwerX = Onwer.X + Onwer.Width / 2;
            double onwerY = Onwer.Y + Onwer.Height / 2;

            if (TargetPoint.X == onwerX && TargetPoint.Y == onwerY)
            {
                var index = Path.IndexOf(TargetPoint) + 1;
                if (index == Path.Count()) return true;
                TargetPoint = Path[index];
            }
            Vector2 vSrc = new Vector2((float)onwerX, (float)onwerY);
            Vector2 vDst = new Vector2((float)TargetPoint.X, (float)TargetPoint.Y);
            Vector2 dir = Vector2.Normalize(vDst - vSrc);
            double dX = TargetPoint.X - onwerX;
            double dY = TargetPoint.Y - onwerY;
            if (Math.Abs(dX) > Onwer.Speed)
                Onwer.X += Onwer.Speed * dir.X;
            else
                Onwer.X += dX;
            if (Math.Abs(dY) > Onwer.Speed)
                Onwer.Y += Onwer.Speed * dir.Y;
            else
                Onwer.Y += dY;

            return false;
        }

        public bool Follow(BaseGameObject target)
        {
            double targetX = target.X + target.Width / 2;
            double targetY = target.Y + target.Height / 2;
            double onwerX = Onwer.X + Onwer.Width / 2;
            double onwerY = Onwer.Y + Onwer.Height / 2;
            Vector2 vSrc = new Vector2((float)onwerX, (float)onwerY);
            Vector2 vDst = new Vector2((float)targetX, (float)targetY);
            Vector2 dir = Vector2.Normalize(vDst - vSrc);
            if (Math.Abs(targetX - onwerX) <= Math.Abs(Onwer.Speed * dir.X)) Onwer.X = targetX;
            Onwer.X += Onwer.Speed * dir.X;
            if (Math.Abs(targetY - onwerY) <= Math.Abs(Onwer.Speed * dir.Y)) Onwer.Y = targetY;
            Onwer.Y += Onwer.Speed * dir.Y;
            Rect r1 = new Rect(Onwer.X, Onwer.Y, Onwer.Width, Onwer.Height);
            Rect r2 = new Rect(target.X, target.Y, target.Width, target.Height);
            if (r1.IntersectsWith(r2)) 
                return true;
            return false;
        }
    }
}
